class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ret;
        sort(nums.begin(),nums.end());
        int sz=nums.size();
        for(int i=0;i<sz;)
        {
            for(int j=i+1;j<sz;)
            {
                int left=j+1,right=sz-1;
                long long pjt=(long long)target-nums[i]-nums[j];
                //优化
                if(nums[i]+nums[j]>pjt) break;

                
                while(left<right)
                {
                    int sum=nums[left]+nums[right];
                    if(sum>pjt) right--;
                    else if(sum<pjt) left++;
                    else{
                        ret.push_back({nums[i],nums[j],nums[left],nums[right]});
                        left++,right--;
                        while(left<right&&nums[left]==nums[left-1])
                            left++;
                        while(left<right&&nums[right]==nums[right+1])
                        right--;
                    } 
                }
                j++;
                while(j<sz&&nums[j]==nums[j-1])
                    j++;
            }
            i++;
            while(i<sz&&nums[i]==nums[i-1])
            i++;

        }
        return ret;
    }
};
